package com.haitonghop.main;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.haitonghop.R;
import com.haitonghop.controls.AdsViewControl;
import com.haitonghop.modules.news.HorizontalListView;
import com.haitonghop.modules.news.NewsRssActivity;
import com.haitonghop.modules.news.RSS;
import com.haitonghop.modules.news.RssItemView;
import com.haitonghop.modules.news.rssreader.model.FeedEntry;
import com.haitonghop.utils.GlobalData;

/**
 * Created by thanhle on 6/15/13.
 */
public class ViewNewsDetailActivity extends Activity implements View.OnClickListener {

	LinearLayout menu_more_news;
	View lineScrollHorizontal;
	WebView main_web_view;
	FrameLayout progressBarLayout;
	ProgressBar progressBar;
	private int currentIndex = 0;
	private String currentTitleNews = "";

	private ImageButton next;
	private ImageButton prev;

	private ImageButton leftHeader = null;
	private ImageButton rightHeader = null;

	private AdsViewControl prview;
	private TextView titleNews;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.act_view_news);

		titleNews = (TextView) findViewById(R.id.titleNews);

		menu_more_news = (LinearLayout) findViewById(R.id.menu_more_news);
		menu_more_news.setOnClickListener(this);

		progressBarLayout = (FrameLayout) findViewById(R.id.progressBarLayout);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		prview = (AdsViewControl) findViewById(R.id.prview);

		next = (ImageButton) findViewById(R.id.btnNext);
		prev = (ImageButton) findViewById(R.id.btnPrev);

		leftHeader = (ImageButton) findViewById(R.id.menu_button_left);
		rightHeader = (ImageButton) findViewById(R.id.menu_button_right);
		rightHeader.setVisibility(View.GONE);
		next.setOnClickListener(this);
		prev.setOnClickListener(this);
		leftHeader.setOnClickListener(this);
		rightHeader.setOnClickListener(this);

		main_web_view = (WebView) findViewById(R.id.main_web_view);
		main_web_view.setFocusableInTouchMode(false);
		main_web_view.setFocusable(false);
		main_web_view.getSettings().setJavaScriptEnabled(true);

		final Activity activity = this;
		main_web_view.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int progress) {
				Log.i("Process", "" + progress);

				progressBar.setProgress(progress);
				if (progressBarLayout != null && progress >= 100) {
					progressBarLayout.setVisibility(View.GONE);
					// Toast.makeText(activity, "Đã tải xong.",
					// Toast.LENGTH_SHORT).show();

					// prview.setVisibility(View.VISIBLE);
					// AdsBussiness.getInstance().doGetAdsFromServer(ViewNewsDetailActivity.this,
					// prview);

				} else if (progressBarLayout != null) {
					progressBarLayout.setVisibility(View.VISIBLE);
				}
			}

		});
		main_web_view.setWebViewClient(new WebViewClient() {
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				Toast.makeText(activity, "Opps! Máy chủ đang bận, bạn vui lòng thử lại lúc khác nhé." + description, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				progressBarLayout.setVisibility(View.GONE);
			}
		});

		main_web_view.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Log.i("Click", ">>>>>>>> Click");
			}
		});

		main_web_view.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent motionEvent) {
				if (lineScrollHorizontal.getVisibility() == View.VISIBLE) {
					Animation out = AnimationUtils.loadAnimation(ViewNewsDetailActivity.this, R.anim.slide_up_out);
					lineScrollHorizontal.startAnimation(out);
					lineScrollHorizontal.setVisibility(View.GONE);
				}

				return false;
			}
		});

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			currentIndex = extras.getInt("CURRENT_INDEX");
			currentTitleNews = extras.getString("CURRENT_TITLE");
		}

		if (currentTitleNews != null) {
			titleNews.setText(currentTitleNews);
		}
		initMenuMore();
	}

	@Override
	protected void onStart() {
		super.onStart();
		AdsBussiness.getInstance().doGetAdsFromServer(ViewNewsDetailActivity.this, prview);

		if(NewsRssActivity.currentRssItem != null && !NewsRssActivity.currentRssItem.isEmpty()) {
			if(currentIndex < NewsRssActivity.currentRssItem.size()){
				FeedEntry item = NewsRssActivity.currentRssItem.get(currentIndex);
				if (item != null) {
					titleNews.setText(item.getTitle());
				}
				progressBar.setProgress(0);
				if (progressBarLayout != null) {
					progressBarLayout.setVisibility(View.VISIBLE);
				}
				main_web_view.loadUrl(item.getLink());
			}			
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	void doLoadNews(int index, FeedEntry item) {
		showHideMenu();

		if (item != null) {
			progressBar.setProgress(0);
			if (progressBarLayout != null) {
				progressBarLayout.setVisibility(View.VISIBLE);
			}
			if (item != null) {
				titleNews.setText(item.getTitle());
			}
			main_web_view.loadUrl(item.getLink());
		}
	}

	void initMenuMore() {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		lineScrollHorizontal = inflater.inflate(R.layout.news_detail_shelf_item_notitle, menu_more_news, false);
		lineScrollHorizontal.setVisibility(View.GONE);

		HorizontalScrollView tblScrollView = (HorizontalScrollView) lineScrollHorizontal.findViewById(R.id.tblScrollView);
		tblScrollView.setVisibility(View.VISIBLE);

		HorizontalListView tblLayoutLine = (HorizontalListView) lineScrollHorizontal.findViewById(R.id.tblLayoutLine);
		tblLayoutLine.setVisibility(View.GONE);

		doAddItemToList(NewsRssActivity.currentRssItem, null);

		if (newsTitle != null) {
			newsTitle.setVisibility(View.GONE);
		}
	}

	void doLoaderNew(int index) {
		if (lineScrollHorizontal.getVisibility() == View.VISIBLE) {
			Animation out = AnimationUtils.loadAnimation(ViewNewsDetailActivity.this, R.anim.slide_up_out);
			lineScrollHorizontal.startAnimation(out);
			lineScrollHorizontal.setVisibility(View.GONE);
		}
		AdsBussiness.getInstance().doGetAdsFromServer(ViewNewsDetailActivity.this, prview);
		FeedEntry item = NewsRssActivity.currentRssItem.get(index);
		if (item != null) {
			progressBar.setProgress(0);
			if (progressBarLayout != null) {
				progressBarLayout.setVisibility(View.VISIBLE);
			}

			if (item != null) {
				titleNews.setText(item.getTitle());
			}

			main_web_view.loadUrl(item.getLink());
		}
	}

	private final static int STOP = 1;
	private final static int BOOKMARK = 2;
	private final static int CLOSE = 3;
	private final static int REFRESH = 4;

	@Override
	public void onClick(View view) {
		if (view != null) {
			int id = view.getId();
			if (id == R.id.menu_more_news) {
				showHideMenu();
			} else if (id == R.id.btnNext) {

				if (progressBarLayout.getVisibility() == View.VISIBLE)
					return;
				if (currentIndex <= NewsRssActivity.currentRssItem.size() - 1) {
					doLoaderNew(++currentIndex);
				}
			} else if (id == R.id.btnPrev) {

				if (progressBarLayout.getVisibility() == View.VISIBLE)
					return;
				if (currentIndex > 0) {
					doLoaderNew(--currentIndex);
				}
			} else if (id == R.id.menu_button_left) {
				main_web_view.stopLoading();
				progressBarLayout.setVisibility(View.GONE);

				finish();
			} else if (id == R.id.menu_button_right) {
				// PopupMenu popupMenu = new PopupMenu(this, view);
				// if (progressBarLayout.getVisibility() == View.VISIBLE)
				// popupMenu.getMenu().add(Menu.NONE, STOP, Menu.NONE,
				// "Ngừng tải");
				// else
				// popupMenu.getMenu().add(Menu.NONE, REFRESH, Menu.NONE,
				// "Refresh");
				//
				// // popupMenu.getMenu().add(Menu.NONE, BOOKMARK, Menu.NONE,
				// // "Đánh dấu trang");
				// popupMenu.getMenu().add(Menu.NONE, CLOSE, Menu.NONE, "Đóng");
				// popupMenu.setOnMenuItemClickListener(this);
				//
				// popupMenu.show();
			}
		}
	}

	// @Override
	// public boolean onMenuItemClick(MenuItem item) {
	// switch (item.getItemId()) {
	// case STOP:
	// main_web_view.stopLoading();
	// progressBarLayout.setVisibility(View.GONE);
	// break;
	// case BOOKMARK:
	// break;
	// case CLOSE:
	// finish();
	// break;
	// case REFRESH:
	// main_web_view.reload();
	// break;
	// }
	// return false;
	// }

	void showHideMenu() {
		if (lineScrollHorizontal.getVisibility() == View.GONE) {
			Animation out = AnimationUtils.loadAnimation(ViewNewsDetailActivity.this, R.anim.slide_up_in);
			lineScrollHorizontal.startAnimation(out);

			lineScrollHorizontal.setVisibility(View.VISIBLE);
		} else {
			Animation out = AnimationUtils.loadAnimation(ViewNewsDetailActivity.this, R.anim.slide_up_out);
			lineScrollHorizontal.startAnimation(out);

			lineScrollHorizontal.setVisibility(View.GONE);
		}
	}

	TextView newsTitle = null;

	public void doAddItemToList(final List<FeedEntry> items, final RSS nameRss) {

		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LinearLayout tblLayoutLine = (LinearLayout) lineScrollHorizontal.findViewById(R.id.tblLayoutLineScrollView);
		for (int iter = 0, size = items.size(); iter < size; iter++) {
			FeedEntry item = items.get(iter);

			View rssItemView = inflater.inflate(R.layout.news_render_detail_modules, tblLayoutLine, false);
			final ImageView imageView = (ImageView) rssItemView.findViewById(R.id.imageView);
			TextView titleView = (TextView) rssItemView.findViewById(R.id.titleView);

			((RssItemView) rssItemView).setContentLink(item);
			((RssItemView) rssItemView).setIndex(iter);

			rssItemView.setOnClickListener(itemRssClick);

			// set data
			titleView.setText(item.getTitle());

			String urlImage = item.getImage();

			GlobalData.mAQ.id(imageView).image(R.drawable.no_preview);
			if (urlImage != null && urlImage.length() > 0) {
				GlobalData.mAQ.id(imageView).image(urlImage, GlobalData.opt_image);
			}

			tblLayoutLine.addView(rssItemView);
		}
		menu_more_news.addView(lineScrollHorizontal, menu_more_news.getChildCount());
		menu_more_news.invalidate();
	}

	View.OnClickListener itemRssClick = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			if (view != null && view instanceof RssItemView) {
				Object tag = ((RssItemView) view).getContentLink();
				if (tag != null && tag instanceof FeedEntry) {
					FeedEntry link = (FeedEntry) tag;

					currentIndex = ((RssItemView) view).getIndex();

					if (link != null) {
						titleNews.setText(link.getTitle());
					}

					doLoadNews(currentIndex, link);
				}
			}
		}
	};
}
